package com.net.entity;

import com.tank.control.DirectionEnum;
import com.tank.entrity.Tank;
import com.tank.model.GameModel;
import lombok.*;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.UUID;

/**
 * 坦克开始运行的消息
 */
@Data
@Slf4j
@ToString
@EqualsAndHashCode(callSuper = true)
public class TankStartMovingMessage extends Message {
    private UUID uuid;
    private int x, y;
    private DirectionEnum directionEnum;

    public TankStartMovingMessage() {

    }

    public TankStartMovingMessage(UUID uuid, int x, int y, DirectionEnum directionEnum) {
        this.uuid = uuid;
        this.x = x;
        this.y = y;
        this.directionEnum =directionEnum;
    }

    public TankStartMovingMessage(Tank tank) {
        this.uuid = tank.getUuid();
        this.x = (int) tank.getX();
        this.y = (int) tank.getY();
        this.directionEnum = tank.getDirectionEnum();
    }
    @Override
    public void handle() {
        if (this.uuid.equals(((Tank)GameModel.getInstance().getMainTank()).getUuid())) {
            return;
        }
        Tank tank = (Tank) GameModel.getInstance().findTankByUUID(this.uuid);
        if (tank != null) {
            tank.setMoving(true);
            tank.setX(this.x);
            tank.setY(this.y);
            tank.setDirectionEnum(directionEnum);
        }
    }

    @Override
    @SneakyThrows
    public byte[] toBytes() {
        @Cleanup ByteArrayOutputStream baos = new ByteArrayOutputStream();
        @Cleanup DataOutputStream dos = new DataOutputStream(baos);

        dos.writeLong(uuid.getMostSignificantBits());
        dos.writeLong(uuid.getLeastSignificantBits());
        dos.writeInt(x);
        dos.writeInt(y);
        dos.writeInt(directionEnum.ordinal());
        dos.flush();
        return baos.toByteArray();
    }

    @Override
    @SneakyThrows
    public void parse(byte[] bytes) {
        @Cleanup DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
        this.uuid = new UUID(dis.readLong(), dis.readLong());
        this.x = dis.readInt();
        this.y = dis.readInt();
        this.directionEnum = DirectionEnum.values()[dis.readInt()];
    }

    @Override
    public MessageType getMessageType() {
        return MessageType.TankStartMoving;
    }
}


